package cn.zcf.org.service.impl;

import cn.zcf.basic.constant.RegisterConstant;
import cn.zcf.basic.constant.WxConstant;
import cn.zcf.basic.exception.BusinessException;
import cn.zcf.basic.jwt.JwtUtils;
import cn.zcf.basic.jwt.LoginData;
import cn.zcf.basic.jwt.RsaUtils;
import cn.zcf.basic.utils.HttpUtil;
import cn.zcf.basic.utils.JsonResult;
import cn.zcf.basic.utils.Md5Utils;
import cn.zcf.basic.utils.StrUtils;
import cn.zcf.org.domain.Emp;
import cn.zcf.org.dto.LoginDto;
import cn.zcf.org.mapper.EmpMapper;
import cn.zcf.org.service.ILoginService;

import cn.zcf.system.domain.Menu;
import cn.zcf.user.domain.Logininfo;
import cn.zcf.user.domain.User;
import cn.zcf.user.domain.WxUser;
import cn.zcf.user.dto.WxDto;
import cn.zcf.user.mapper.LogininfoMapper;
import cn.zcf.user.mapper.UserMapper;
import cn.zcf.user.mapper.WxUserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public JsonResult accountLogin(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        Integer loginType = loginDto.getLoginType();
        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(username)
                ||StringUtils.isEmpty(password)
                ){
            throw new BusinessException("请输入合法信息!!!");
        }

        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("用户名或密码错误!!!");
        }
        //1.2.用户名或密码【加密加盐】校验
        String dbMd5Pwd = logininfo.getPassword();
        String md5Pwd = Md5Utils.encrypByMd5(password + logininfo.getSalt());
        if(!dbMd5Pwd.equals(md5Pwd)){
            throw new BusinessException("用户名或密码错误!!!");
        }

        //1.3.状态校验 - 启用，禁用
        if(logininfo.getDisable()==0){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }

        /*//2.将token和登录信息对象 保存在 redis 30分钟有效
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        //3.使用Map将token和登录对象绑定到JsonResult的resultObj中响应给前端
        //说明：token相当于jessionid   登录对象响应到前端 - 在系统中回显用户名
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        //  使用jwt
        Map<String,Object> map = loginSuccessJwtHandler(logininfo);

        return JsonResult.me().setResultObj(map);
    }

    @Override
    public JsonResult wechatLogin(String code) {
        //1.根据code发送请求获取token和openid
        String url = WxConstant.GET_ACK_URL
                .replace("APPID",WxConstant.APPID)
                .replace("SECRET",WxConstant.SECRET)
                .replace("CODE",code);
        String jsonStr = HttpUtil.httpGet(url);
        //        System.out.println(jsonStr);

        //{"access_token":"57_3R0PHzOIKX6brh1TbBZKqwsOCHugjzrJeDZgssoAmsF_UFOq-TSTXE3tmZBUr7VIZ_eP71LhIzOeLeh4gua3vVligjDuBCjRiImEAPSAwqc","openid":"oa9wA01X4TNik8bbXWklIyArUZ5c",}
        //2.将响应的json字符串 转成 json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //3.通过openid去t_wxuser中查询
        WxUser wxuser = wxUserMapper.loadByOpenid(openid);

        if(wxuser!=null && wxuser.getUser_id()!=null){ //绑定了
            //4.有 绑定过 - 直接免密登录【获取logininfo对象 登录】
            Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUser_id());

/*            String token = UUID.randomUUID().toString();
            //去掉密码和盐值 - 安全
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);*/
            //  使用jwt
            Map<String,Object> map = loginSuccessJwtHandler(logininfo);

            return JsonResult.me().setResultObj(map);
        }else{
            //5.没有 - 需要跳转页面绑定 - 响应给前端进行跳转
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return JsonResult.me().setMsg("绑定").setResultObj(map);
        }
    }

    @Override
    public JsonResult binder(WxDto dto) {
        String phone = dto.getPhone();
        String verifyCode = dto.getVerifyCode();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        // 1. 校验， 非空校验，验证码校验---超时， 是否正确。
        if(StringUtils.isEmpty(phone)
                ||StringUtils.isEmpty(verifyCode)
                ||StringUtils.isEmpty(accessToken)
                ||StringUtils.isEmpty(openId)){
            throw  new BusinessException("参数不能为空");
        }

        // 校验验证码
        Object obj = redisTemplate.opsForValue().get(phone + RegisterConstant.WXBINDER);
        if(obj==null){
            throw  new BusinessException("验证码过期，请重新获取！");
        }
        if(!verifyCode.equalsIgnoreCase(obj.toString().split(":")[0])){
            throw  new BusinessException("验证码输入错误，请重新输入！");
        }

        // 2. wxuser, user, logininfo

        // 向微信开放平台发送第三次请求。获取wxuser信息。
        String jsonObj = HttpUtil.httpGet(WxConstant.GET_WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId)
        );
        // 获取wxuser
        WxUser wxUser = jsonObj2WxUser(jsonObj);

        // 通过手机号查询user信息。能查到：直接绑定。
        User dbUser = userMapper.loadByPhone(phone);
        // 通过手机号查询user信息。查不到：自己生成一个user，logininfo，再绑定。
        if(dbUser==null){
            // 没有用手机号注册过,生成一个user对象，存值。--关联一个loginInfo
            dbUser = phone2User(phone);
            // logininfo
            Logininfo dbLogininfo = user2Logininfo(dbUser);

            // 保存logininfo，返回自增主键
            logininfoMapper.save(dbLogininfo);

            // 保存user  把logininfo_id放进去
            dbUser.setLogininfo_id(dbLogininfo.getId());
            userMapper.add(dbUser); // 返回自增的主键
        }

        // 绑定wxuser
        wxUser.setUser_id(dbUser.getId());
        wxUserMapper.save(wxUser);

        // 通过user中的logininfoid查询logininfo
        Logininfo logininfo = logininfoMapper.loadById(dbUser.getLogininfo_id());


/*        // 免密登录。
        String token = UUID.randomUUID().toString();
        // 设置三十分钟过去
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        // 准备一个map
        HashMap<String, Object> map = new HashMap<>();

        map.put("token",token);
        // 把盐值，和密码设置为null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/
        //  使用jwt
        Map<String,Object> map = loginSuccessJwtHandler(logininfo);

        // controller
        return JsonResult.me().setResultObj(map);


    }

    @Override
    public JsonResult logOut(String token) {
        /*redisTemplate.delete("token");*/
        return JsonResult.me();
    }

    // 生成一个logininfo对象
    private Logininfo user2Logininfo(User dbUser) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(dbUser,logininfo);
        return logininfo;

    }

    // 生成一个user对象
    private User phone2User(String phone) {

        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 生成一个颜值， 密码
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);

        // 生一个密码
        String password = StrUtils.getComplexRandomString(6);

        // 加密
        String dbPassword = Md5Utils.encrypByMd5(salt + password);
        user.setPassword(dbPassword);

        return user;
    }

    // 返回一个wxuser对象
    private WxUser jsonObj2WxUser(String jsonObj) {
        // 把jsonobj转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonObj);

        WxUser wxUser = new WxUser();
        wxUser.setAddress(jsonObject.getString("country"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setNickname("xx"); // 昵称，特使字符
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setUnionid(jsonObject.getString("unionid"));

        return wxUser;

    }



    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        //创建LoginData对象用于等会通过私钥加密
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            //1.获取logininfo
            if(logininfo.getType()==0){//管理员
                // 返回当前登录人的权限
                List<String> permissions = empMapper.getPermissionsByLogininfoId(logininfo.getId());

                // 当前登录人所有菜单
                List<Menu> menus = empMapper.getMenusByLogininfoId(logininfo.getId());

                // 存入loginData
                loginData.setMenus(menus);
                loginData.setPermissions(permissions);

                // 存入map
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //4.通过私钥对登录信息进行加密 - jwtToken串
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader()                                             	  .getResource("auth_rsa.pri").getFile());
            //将登陆人信息加密得到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            //5.装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

